package logic

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"oil-station-backend/internal/model"
	"oil-station-backend/internal/svc"
	"oil-station-backend/internal/types"

	"github.com/golang-jwt/jwt/v4"
)

type FuelLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFuelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FuelLogic {
	return &FuelLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FuelLogic) GetFuelTypes() ([]types.FuelType, error) {
	fuelTypes, err := l.svcCtx.FuelTypeModel.FindAll()
	if err != nil {
		return nil, err
	}

	var result []types.FuelType
	for _, ft := range fuelTypes {
		result = append(result, types.FuelType{
			Id:    ft.Id,
			Type:  ft.Type,
			Name:  ft.Name,
			Price: ft.Price,
		})
	}

	return result, nil
}

func (l *FuelLogic) CreateOrder(req *types.CreateOrderReq, r *http.Request) (*types.Order, error) {
	// 从上下文中获取JWT声明（由JWT中间件设置）
	claims, ok := l.ctx.Value("claims").(jwt.MapClaims)
	if !ok {
		return nil, fmt.Errorf("未授权：无法获取用户信息")
	}

	// 获取用户ID和用户名
	userId, ok := claims["id"].(float64)
	if !ok {
		return nil, fmt.Errorf("无效的用户ID")
	}

	username, ok := claims["username"].(string)
	if !ok {
		return nil, fmt.Errorf("无效的用户名")
	}

	// 查找用户信息
	user, err := l.svcCtx.UserModel.FindByUsername(username)
	if err != nil {
		return nil, fmt.Errorf("用户不存在: %v", err)
	}

	// 生成订单号
	orderNo := l.generateOrderNo()

	// 创建订单
	order := &model.Order{
		OrderNo:       orderNo,
		UserId:        int64(userId),
		UserName:      user.Name,
		FuelType:      req.FuelType,
		FuelPrice:     req.FuelPrice,
		Volume:        req.Volume,
		PrepaidAmount: req.PrepaidAmount,
		Status:        "pending",
	}

	err = l.svcCtx.OrderModel.Create(order)
	if err != nil {
		return nil, fmt.Errorf("创建订单失败: %v", err)
	}

	return &types.Order{
		Id:            order.Id,
		OrderNo:       order.OrderNo,
		UserId:        order.UserId,
		UserName:      order.UserName,
		FuelType:      order.FuelType,
		FuelPrice:     order.FuelPrice,
		Volume:        order.Volume,
		PrepaidAmount: order.PrepaidAmount,
		Status:        order.Status,
		CreateTime:    order.CreateTime.Format("2006-01-02 15:04:05"),
		UpdateTime:    order.UpdateTime.Format("2006-01-02 15:04:05"),
	}, nil
}

// 生成订单号
func (l *FuelLogic) generateOrderNo() string {
	return fmt.Sprintf("ORD%d", time.Now().UnixNano()/1000000)
}